﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace MikeSoft.Tool.Common
{
    public class SerialPorts
    {
        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="serialPort">串口对象</param>
        /// <param name="portName">串口</param>
        /// <param name="baudRate">波特率</param>
        /// <param name="dataBits">数据位</param>
        /// <returns></returns>
        public bool SerialPortOpen(SerialPort serialPort, string portName, int baudRate, int dataBits)
        {
            try
            {
                serialPort.PortName = portName;
                serialPort.BaudRate = baudRate;
                serialPort.Parity = Parity.None;
                //serialPort.DataBits =8;
                serialPort.StopBits = StopBits.One;
                serialPort.Open();
                if (serialPort.IsOpen)
                    return true;
                return false;
            }
            catch (Exception ex)
            {
                throw new Exception("串口打开失败", ex);
            }
        }
        /// <summary>
        /// 关闭串口
        /// </summary>
        /// <param name="serialPort"></param>
        public void SerialPortClose(SerialPort serialPort)
        {
            serialPort.Close();
        }
        /// <summary>
        /// 波特率
        /// </summary>
        public string[] SerialPortBaudRate = new string[] { "9600", "19200", "38400", "57600", "115200" };
        /// <summary>
        /// 获取串口
        /// </summary>
        /// <returns></returns>
        public string[] GetPortNames()
        {
            string[] _serialPorts = null;
            try
            {
                _serialPorts = SerialPort.GetPortNames();
            }
            catch (Exception ex)
            {
                throw new Exception("获取串口失败", ex);
            }
            return _serialPorts;
        }
    }
}
